<template>
  <slot>
    <el-button link type="primary" icon="Top" @click="handleOpen" :loading="btnLoading">{{ btnName }}</el-button>
  </slot>
  <basic-dialog v-model="visible" :title="title" :width="width" :autoClose="false" :submitBtnLoading="submitBtnLoading"
    @submit="handleSubmit">
    <avue-upload :class="{ customDisabled: props.disabled || fileList.length === props.limit }" :propsHttp="propsHttp"
      :listType="listType" :headers="{
        ...headers,
        'h-authorization-token': token,
      }" :action="action" v-bind="attrs" v-model="form" :dataType="dataType" :upload-after="handleUploadAfter"
      :upload-delete="handleUploadDelete" :props="{
        value: 'url',
        label: 'name',
      }"></avue-upload>
  </basic-dialog>
</template>

<script setup>
import request from '@/utils/request'
import { useUserStore } from '@/store/user.js'
import { baseUrl } from '@/env.config.js'
defineOptions({
  inheritAttrs: false,
})
const { token } = storeToRefs(useUserStore())
const attrs = useAttrs()
const props = defineProps({
  btnName: {
    type: String,
    default: '文件上传',
  },
  // 弹窗宽度
  width: {
    type: String,
    default: '500',
  },
  // 弹窗标题
  title: {
    type: String,
    default: '文件上传',
  },
  // 所属模块
  belongModule: String,
  // 绑定数据的接口
  bindDataApi: String,
  // 获取文件的接口
  getFileInfoApi: String,
  fileIdsName: {
    type: String,
    default: 'fileId',
  },
  // 当前行数据
  curData: {
    type: Object,
    default: () => ({}),
  },
  propsHttp: {
    type: Object,
    default: () => ({
      res: 'obj',
      name: 'obj.name',
      url: 'fileViewUrl',
    }),
  },
  headers: {
    type: Object,
    default: () => ({}),
  },
  dataType: {
    type: String,
    default: 'object',
  },
  props: {
    type: Object,
    default: () => ({
      label: 'name',
      value: 'url',
    }),
  },
  listType: {
    type: String,
    default: 'picture-card',
  },
  limit: Number,
  saveAfter: Function,
  disabled: Boolean,
})
const action = computed(() => {
  return baseUrl + `/${props.belongModule}/fileController/uploadFile`
})
const visible = ref(false)
const form = ref([])
const fileList = ref([])
const submitBtnLoading = ref(false)
const handleOpen = () => {
  visible.value = true
}

const handleSubmit = () => {
  if (form.value.length === 0) {
    return ElMessage.warning('请选择文件上传！')
  }
  submitBtnLoading.value = true
  request({
    url: props.bindDataApi,
    method: 'post',
    data: {
      id: props.curData.id,
      fileIds: fileList.value.map((item) => item.id).join(','),
      field: props.fileIdsName,
    },
  })
    .then(() => {
      ElMessage.success('文件保存成功！')
      visible.value = false
      props.saveAfter && props.saveAfter()
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
    .finally(() => {
      submitBtnLoading.value = false
    })
}

// 上传之后
const handleUploadAfter = (res, done, loading, column) => {
  fileList.value.push(res)
  done()
}
// 删除
const handleUploadDelete = (file, column) => {
  const { url } = file
  const idx = fileList.value.findIndex((item) => item.fileViewUrl === url)
  if (idx > -1) {
    fileList.value.splice(idx, 1)
  }
  return Promise.resolve()
}

const btnLoading = ref(false)
const getFileinfo = () => {
  btnLoading.value = true
  request({
    url: props.getFileInfoApi,
    method: 'get',
    resField: 'data',
    params: {
      id: props.curData.id,
      field: props.fileIdsName,
    },
  })
    .then((res) => {
      form.value = res
      fileList.value = res.map((item) => {
        item.fileViewUrl = item.url
        return item
      })
    })
    .catch((err) => {
      console.log(err, 'err')

      ElMessage.error(err.msg)
    })
    .finally(() => {
      btnLoading.value = false
    })
}
watch(
  () => visible.value,
  (newV) => {
    if (newV) {
      getFileinfo()
    } else {
      fileList.value = []
      form.value = []
    }
  }
)
</script>

<style lang="scss" scoped>
.customDisabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
